// pages/detail/detail.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    go_top_show: false,

    likeNum:0,  //点赞数
    isLike : false,  //点赞
    isCollect:false,  //收藏
    collectNum:0,  //收藏数

    likeUrl:"../../images/img/like.png",
    collectUrl:"../../images/img/collect.png",
    share:"../../images/img/share.png",

    shareNum:0,     //分享数
    cover_img:'',
    article_title:'',


    article:{},
    article_id:'',
    commentList:{},
    time:'',
    commentTime:[],
    comment:'',
    userinfo:{
      nickName:"",
      avatarUrl:'',
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: false//wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },

  getUserProfile(e) {
    let _that=this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        //将登录信息添加到全局变量
        app.appData.userinfo=res.userInfo

        wx.login({
          success: (res) => {          
            if(res.code){
              wx.request({
                      url: 'https://linshiqiang.cn/api/login/logincheck',
                      data: {
                              code: res.code,
                              user_name:_that.data.userInfo.nickName,
                              user_img:_that.data.userInfo.avatarUrl,
                      },
                      method:'GET',
                      success: function(res) {    
                        _that.onPullDownRefresh()                           
                        console.log("微信用户登录成功");                             
                      }
                     
                  })
              }
            }
          })

      }

    })
  },  
  //点击增加留言
  formSubmit:function(e){
    let _that=this
    if (_that.data.userinfo.nickName == '' || _that.data.userinfo.nickName == undefined || _that.data.userinfo.nickName == "请点击头像登录") {
      wx.showToast({
        title: '评论失败：您尚未登录',
        icon: 'none',
        duration: 3000 //持续的时间
      })
      _that.setData({
        comment: ''
      })
        _that.getUserProfile()

      return false;
    }
   _that.setData({
     comment:e.detail.value.comment
   })
  //  console.log("名称：",_that.data.userinfo.nickName)
  //  console.log("内容：",_that.data.comment)//评论内容
  //  console.log("文章id：",_that.data.article_id)//文章id
   wx.request({
    url: 'https://linshiqiang.cn/api/comment/add?article_id='+_that.data.article_id+'&comment_content='+_that.data.comment
    +'&user_name='+_that.data.userinfo.nickName+'&user_img='+_that.data.userinfo.avatarUrl,
    success:function(res){
      // console.log(res)
      if(res.data.status == 10003){
        wx.showToast({
          title: '评论失败：评论内容包含敏感词！',
          icon: 'none',  
          duration: 3000//持续的时间
        })
        _that.setData({
          comment:''
        })
        return false;
      }
      if(res.data.status == 10002){
        wx.showToast({
          title: '评论失败!',
          icon: 'none',  
          duration: 3000//持续的时间
        })
        _that.setData({
          comment:''
        })
        return false;
      }
      let list = _that.data.commentList;
      list.unshift(res.data.data.comment)
      _that.setData({
        commentList:list
      })
      _that.setData({
        comment:"",
      })
      wx.showToast({
        title: '增加评论成功',
        icon: 'none',  
        duration: 3000//持续的时间
      })
    }
  })
  },
    //点赞
    clikLike(){
      var that = this;
      if(app.appData.userinfo.nickName == '' || app.appData.userinfo.nickName == undefined || that.data.userinfo.nickName == "请点击头像登录"){
        wx.showToast({
          title: '点赞失败：请先登录',
          icon: 'none',  
          duration: 2000//持续的时间
        })
        that.getUserProfile()
        return false;
      }

      var articleId = that.options.article_id
      var  isLike = that.data.isLike
      if(isLike){
        var onum = that.data.likeNum;
        that.data.likeNum = (onum - 1);
        that.setData({
          likeUrl:"../../images/img/like.png",
          likeNum:that.data.likeNum,
          isLike:false
        })
        wx.request({
          url:'https://linshiqiang.cn/api/article/likedelete?user_name='+app.appData.userinfo.nickName+'&article_id='+articleId,
          success: function (res) {
           wx.showToast({
             title: '取消点赞成功',
             icon: 'success',
             duration: 2000 //持续的时间
           })
         },
         fail: function (res) {
           console.log("取消点赞失败");
         }
         })
      }else{
        var onum = that.data.likeNum;
        that.data.likeNum = (onum + 1);
        that.setData({
          likeUrl:"../../images/img/like1.png",
          likeNum:that.data.likeNum,
          isLike:true
        })
        wx.request({
          url:'https://linshiqiang.cn/api/article/like?user_name='+app.appData.userinfo.nickName+'&article_id='+articleId,
           success: function (res) {
            wx.showToast({
              title: '增加点赞成功',
              icon: 'success',
              duration: 2000 //持续的时间
            });
          },
          fail: function (res) {
            console.log("增加点赞失败");
          }
          })
      }

    },



     //收藏
     clikCollect(){
       let _that = this;
      //  console.log("-----",app.appData.userinfo.nickName)
       //判断是否登录，如果未登录，不能收藏，提示登录
       if(app.appData.userinfo.nickName == '' || app.appData.userinfo.nickName == undefined || _that.data.userinfo.nickName == "请点击头像登录" ){
        wx.showToast({
          title: '收藏失败：您尚未登录',
          icon: 'none',  
          duration: 1000//持续的时间
        })
        this.setData({
          collectUrl:"../../images/img/collect.png",
        })
        this.getUserProfile()
        return false;
      }

      var that = this;
      var articleId = that.options.article_id
      var  isCollect = that.data.isCollect
       if(isCollect){
      var onum = that.data.collectNum;
      that.data.collectNum = (onum - 1);
         that.setData({
             collectUrl:"../../images/img/collect.png",
             collectNum:that.data.collectNum,
             isCollect:false
           })
           wx.request({
            url:'https://linshiqiang.cn/api/article/collectdelete?user_name='+app.appData.userinfo.nickName+'&article_id='+articleId,
            success: function (res) {
             wx.showToast({
               title: '取消收藏成功',
               icon: 'success',
               duration: 2000 //持续的时间
             })
           },
           fail: function (res) {
             console.log("取消收藏失败");
           }
           })
       }else{
         var onum = that.data.collectNum;
         that.data.collectNum = (onum + 1);
         that.setData({
           collectUrl:"../../images/img/collect1.png",
           collectNum:that.data.collectNum,
           isCollect:true
         })
         wx.request({
          url:'https://linshiqiang.cn/api/article/collect?user_name='+app.appData.userinfo.nickName+'&article_id='+articleId,
           success: function (res) {
            wx.showToast({
              title: '增加收藏成功',
              icon: 'success',
              duration: 2000 //持续的时间
            });
          },
          fail: function (res) {
            console.log("增加收藏失败");
          }
          })
       }
     },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  //  console.log(options.article_id)  //获取到的文章id
    this.setData({
      userinfo:app.appData.userinfo,
      article_id:options.article_id
    })
   //获取到文章详情页的数据
   let that = this
   wx.request({
     url: 'https://linshiqiang.cn/api/article/detail?article_id='+options.article_id,
     success:function(res){
       //时间戳转换成日期格式
      let addTime=res.data.data.article.add_time
      let date = new Date(addTime * 1000);
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, '0');
      let day = date.getDate().toString().padStart(2, '0');
      let hour = date.getHours().toString().padStart(2, '0');
      let minute = date.getMinutes().toString().padStart(2, '0');
      // let second = date.getSeconds().toString().padStart(2, '0');
      let ymdtime= year + "-" + month + "-" + day +" " + hour+":"+minute
      // console.log("时间",ymdtime)
       that.setData({
         article:res.data.data.article,
         article_title:res.data.data.article.article_title,
         cover_img:res.data.data.article.cover_image,
         time:ymdtime
        })
     }
   })

  //获取到评论列表的数据
   let self = this
   wx.request({
    url:'https://linshiqiang.cn/api/comment/list?article_id='+options.article_id,
     success:function(res){
       self.setData({
         commentList:res.data.data.commentList
       })
      //  console.log("----",res.data.data.commentList)
     }
   })

  
   //获取到点赞列表的数据
  wx.request({
    url: 'https://linshiqiang.cn/api/article/likelist?article_id=' + options.article_id, //这里写后台点赞接口的url',
    success: function (res) {
      let likelist = res.data.data.likeList //点赞列表数据
        // console.log("点赞",likelist)
      let nickName = app.appData.userinfo.nickName
      let articleId = options.article_id
      let likelists = []
      that.setData({
        likeNum: likelist.length,
      })
      for (var i = 0; i < likelist.length; i++) {
        if (likelist[i]['user_name'] == nickName) {
          likelists[1] = likelist[i]
        }
      }
      if(likelists[1] == undefined || likelists[1] == '' ){
        let isLike = false
        let  likeUrl = "../../images/img/like.png"
        that.setData({
          likeNum: likelist.length,
          isLike: isLike,
          likeUrl:likeUrl
        })
      }else if(nickName == likelists[1].user_name  && articleId ==likelists[1].article_id  ){
        let  likeUrl = "../../images/img/like1.png"
        let  isLike = true
        that.setData({
          likeNum:likelist.length,
          isLike: isLike,
          likeUrl:likeUrl
        })
      }
    }
  })

   //获取到收藏列表的数据
  wx.request({
    url: 'https://linshiqiang.cn/api/article/collectlist?article_id=' + options.article_id, //这里写后台点赞接口的url',
    success: function (res) {
      let collectlist = res.data.data.collectList //收藏列表数据
      // console.log("收藏列表",collectlist)
      let articleId = options.article_id
      let nickName = app.appData.userinfo.nickName
      let collectlists = []
      that.setData({
        collectNum: collectlist.length,
      })
      for (var i = 0; i < collectlist.length; i++) {
        if (collectlist[i]['user_name'] == nickName && collectlist[i]['article_id'] ==  articleId) {
          collectlists[1] = collectlist[i]
        }
      }
      if(collectlists[1] == undefined || collectlists[1] == '' ){
        let isCollect = false
        let  collectUrl = "../../images/img/collect.png"
        that.setData({
          collectNum: collectlist.length,
          isCollect: isCollect,
          collectUrl:collectUrl
        })
      }else if(nickName == collectlists[1].user_name  && articleId ==collectlists[1].article_id ){
        let collectUrl = "../../images/img/collect1.png"
        let isCollect = true
        that.setData({
          likeNum:collectlist.length,
          isCollect: isCollect,
          collectUrl:collectUrl
        })
      }
    }
  })

     //获取分享列表
     wx.request({
      url: 'https://linshiqiang.cn/api/article/sharelist?article_id=' + options.article_id, //这里写后台点赞接口的url',
      success: function (res) {
        // console.log(res)
        that.setData({
          shareNum: res.data.data.sharetList.length,
        })
      }
     })
  },

  
    //过滤器
  formatTime : function(now) {
  var time = new Date( now*1000 );
  var year=time.getFullYear();  //取得4位数的年份
  var month=(time.getMonth()+1).toString().padStart(2,"0");  //取得日期中的月份，其中0表示1月，11表示12月
  var date=time.getDate().toString().padStart(2,"0");      //返回日期月份中的天数（1到31）
  var hour=time.getHours().toString().padStart(2,"0");     //返回日期中的小时数（0到23）
  var minute=time.getMinutes().toString().padStart(2,"0"); //返回日期中的分钟数（0到59）
  // var second=time.getSeconds().toString().padStart(2,"0"); //返回日期中的秒数（0到59）
  let times=year + "-"+ month + "-" + date + " " + hour + ":" + minute
  return times
  },


  



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  /**
   * 用户点击右上角分享------------------------------------------------------
   */
  onShareAppMessage: function () {
    let that = this
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title:that.data.article_title, //'标题',
          imageUrl:that.data.cover_img, //`图片地址注意符号` ,
          path: 'pages/index/index', //分享当前页面
        })
      }, 300)
    })
          wx.request({
            url:'https://linshiqiang.cn/api/article/share?article_id='+that.options.article_id,
             success: function (res) {
              setTimeout(() => {
              var onum = that.data.shareNum;
              that.data.shareNum = (onum + 1);
              that.setData({
                shareNum:that.data.shareNum,
              })
              wx.showToast({
                title: '分享成功',
                icon: 'success',
                duration: 2000 //持续的时间
              })
            }, 1000)
            },
             fail: function (res) {
              console.log("分享失败");
            }
          })
          return {
            title: '玖玖博客',
            path: '/pages/detail/detail',
            promise 
          }
      
  },
//用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
        title: '玖玖博客',
        path: '/pages/detail/detail',
	      query: {
	        key: value
	      },
	    }
	},
  //下拉刷新---------------------------------------------------------------------
  onPullDownRefresh:function()
  {
    let that = this;
    this.setData({
      goodsList: []
    })
    this.onLoad(this.options)
    wx.showNavigationBarLoading() //在标题栏中显示加载
    //模拟加载
    setTimeout(function()
    {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 2000//持续的时间
      })
    },1000); 
  },



  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 100) {
      this.setData({
        go_top_show: true
      })
    } else {
      this.setData({
        go_top_show: false
      })
    }
  },
  // 回到顶部
  goTop: function(e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  }


})